#include <stdio.h>
#include <netdb.h>
#include <stdlib.h>
#include <errno.h>
#include <arpa/inet.h>

int main(int argc, char** argv) {

   if (argc < 4) {
      printf("Program checks whether two ips is in one subnet\n");
      printf("args: [ip1] [ip2] [mask]\n");
      printf("example: 192.168.1.1 192.168.1.2 24\n");
      return -1;
   }
   errno = 0;
   in_addr_t ip1 = inet_addr(argv[1]); //big endian, like on net :)
   in_addr_t ip2 = inet_addr(argv[2]);   
   if (errno || !~ip1 || !~ip2) {
      printf("ERROR: invalid ips\n");
      return -1;
   }

   errno = 0;
   uint32_t mask_bits = strtol(argv[3], NULL, 10);
   if (errno)
      perror("ERROR: invalid mask ");

   uint32_t mask = 0;
   for (;mask_bits > 0; --mask_bits)
      mask |= 0x00000001 << (mask_bits - 1);
   
   printf("ip1 %x ip2 %x mask %x \n", ip1, ip2, mask);
   printf("ip1 subnet %x \nip2 subnet %x \n", ip1 & mask, ip2 & mask);
   
   if ((ip1 & mask) == (ip2 & mask))
      printf("The same subnet!\n");
   else
      printf("Different subnets!\n");
   
   return 0;
}
